package com.mftour.moudles.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mftour.common.Constant;
import com.mftour.common.cache.InitCache;
import com.mftour.common.spring.mybatis.DataSourceType;
import com.mftour.common.spring.mybatis.DynamicDataSourceHolder;
import com.mftour.common.utils.CookieUtils;
import com.mftour.common.utils.DesUtil;
import com.mftour.common.utils.HttpUtils;
import com.mftour.common.utils.MD5;
import com.mftour.moudles.entity.User;
import com.mftour.moudles.service.UserService;
import com.zdm.dubbo.provider.service.DemoService;

@Controller
@RequestMapping(value = "/login")
// @Scope("prototype")
// controller默认单例，使用@Scope("prototype")来设置多例
public class LoginController extends BaseController {

	@Autowired
	private UserService userSer;

	// @Autowired
	// private MemcachedClient memcachedClient;

	private int testIndex = 0;
	private static int si = 0;

	@Autowired
	DemoService demoService;
	
	@RequestMapping(value = "/loginIndex")
	public String loginIndex() {
		System.out.println(demoService.sayHello("abcd"));
		// try {
		testIndex = testIndex + 1;
		si = si + 1;
		// System.out.println(si + " | " + testIndex);
		// CookieUtils.addCookie(response, "testIndex", testIndex);
		// CookieUtils.addCookie(response, "si", si);

		// memcachedClient.set("zdmtest", 0, "test value");
		// System.out.println(memcachedClient.get("zdmtest"));
		// } catch (TimeoutException | InterruptedException | MemcachedException
		// e) {
		// e.printStackTrace();
		// }
		Cookie userId = CookieUtils.getCookieByName(request, "userId");
		if (userId != null) {
			User u = userSer.selectByPrimaryKey(Integer.parseInt(userId.getValue()));
			if (u.getLoginAuto().intValue() == 1) {
				Cookie pwdCookie = CookieUtils.getCookieByName(request, "pwd");
				if (pwdCookie != null) {
					String pwd = pwdCookie.getValue();
					if (pwd.equals(MD5.toMD5(u.getPwd()))) {
						String ip = HttpUtils.getIpAddr(request);
						u.setLoginAt(new Date());
						u.setLoginIp(ip);
						u.setLiveStatus("1");
						userSer.updateByPrimaryKeySelective(u);
						session.setAttribute(Constant.SESSION_LOGIN_USER, u);
						return "redirect:main";
					}
				}
			}
		}

		DynamicDataSourceHolder.setDataSourceType(DataSourceType.READDB);
		return "redirect:/loginIndex.html";
	}

	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public ModelAndView doLogin(User loginUser, boolean rememberFlag) {
		String msg = "";
		if (loginUser.getLoginId() == null || loginUser.getPwd() == null) {
			msg = "请填写用户名密码";
			return new ModelAndView("login", "msg", msg);
		}
		loginUser.setPwd(DesUtil.encrypt(loginUser.getLoginId() + loginUser.getPwd()));
		List<User> users = userSer.selectListSelective(loginUser);
		String ip = HttpUtils.getIpAddr(request);

		if (users.size() > 0) {
			User u = new User();
			u.setUserId(users.get(0).getUserId());
			u.setLoginAt(new Date());
			u.setLoginIp(ip);
			u.setLiveStatus("1");
			if (rememberFlag) {
				CookieUtils.addCookie(response, "userId", users.get(0).getUserId());
				CookieUtils.addCookie(response, "pwd", MD5.toMD5(users.get(0).getPwd()));
				u.setLoginAuto((byte) 1);
			} else {
				u.setLoginAuto((byte) 0);
			}
			userSer.updateByPrimaryKeySelective(u);
			session.setAttribute(Constant.SESSION_LOGIN_USER, users.get(0));
			return new ModelAndView(new RedirectView("main"));
		} else {
			msg = "账号信息不正确";
			return new ModelAndView("login", "msg", msg);
		}

		// return "redirect:../main";
		// return "main";
	}

	@RequestMapping(value = "/main")
	public String toMain() {
		request.setAttribute("userMenuPermissions", InitCache.allUserMenuPermissions.get(loginUser.getUserId()));
		return "main";
	}

	@RequestMapping(value = "/loginOut")
	public String loginOut() {
		// User u=new User();
		// u.setUserId(loginUser.getUserId());
		// u.setLiveStatus("0");
		// userSer.updateUserByPrimaryKeySelective(u);
		session.invalidate();
		CookieUtils.delAll(request, response);
		return "login";
	}

	@RequestMapping(value = "/test")
	public void test() {
	}

	public static void main(String[] args) {
		System.out.println(DesUtil.encrypt("test1123456"));
		System.out.println(DesUtil.encrypt("test2123456"));
	}
}
